const { validate } = require("validate.js");
const { ValidationError, UnknownError } = require("../utils/errors");
const fs = require("fs");
const { addMessageDao, findMessageByPageDao, deleteMessageDao } = require("../dao/messageDao");
const { findBlogByIdDao } = require("../dao/blogDao");
const { formatResponse, handleDataPattern } = require("../utils/tool");
const dir ='./public/static/awatar';

/**
 * 读取一个目录下有多少文件
 * @param {*} dir 
 */
async function readDirLength(dir) {
  return new Promise((resolve) => {
    fs.readdir(dir, (err, files) => {
      if(err) throw new UnknownError();
      resolve(files);
    })
  })
}

// 新增评论或者留言
module.exports.addMessageService = async function (messageInfo) {
  // 数据验证规则
  const messageRule = {
    nickname: {
      presence: {
        allowEmpty: false
      },
      type: "string"
    },
    content: {
      presence: {
        allowEmpty: false
      },
      type: "string"
    },
    blogId: {
      type: "string"
    }
  }
  // 进行数量验证
  const validateResult = validate.validate(messageInfo, messageRule);
  if(!validateResult) {
    messageInfo.blogId = messageInfo.blogId ? messageInfo.blogId : null;
    messageInfo.createDate = Date.now();
    // 有一个头像的地址，该头像是随机生成的
    // 读取static下面的avatar目录
    const files = await readDirLength(dir);
    // 随机生成一个文件
    const randomIndex = Math.floor(Math.random() * files.length);
    messageInfo.avatar = '/static/awatar/' + files[randomIndex];
    // 新增评论或者留言
    const data = await addMessageDao(messageInfo);
    // 如果是文章的评论，那么文章的评论数量也要新增
    if(messageInfo.blogId) {
      const blogDate = await findBlogByIdDao(messageInfo.blogId);
      blogDate.commentNumber++;
      await blogDate.save();
    }
    return formatResponse(0, "", data);
  } else {
    throw new ValidationError("数据验证失败");
  }
}

// 分页获取评论或者留言
module.exports.findMessageByPageService = async function (pageInfo) {
  const data = await findMessageByPageDao(pageInfo);
  const rows = handleDataPattern(data.rows);
  return formatResponse(0, "", {
    "total": data.count,
    "rows": rows
  });
}

// 删除评论或者留言
module.exports.deleteMessageService = async function (id) {
  await deleteMessageDao(id);
  return formatResponse(0, "", true);
}